//
//  MusicDownloader.m
//  kyMusicPlayer
//
//  Created by 翁科宇 on 2018/5/14.
//  Copyright © 2018年 翁科宇. All rights reserved.
//

#import "MusicDownloader.h"

@interface MusicDownloader()
@property(nonatomic, strong)NSOperationQueue *queue;
@property(nonatomic, strong)NSURLSessionDataTask *sessionTask;

@end

@implementation MusicDownloader

- (instancetype)init{
    if (self = [super init]) {
        _songInfo = SongInfo.sharedManager;
    }
    return self;
}

// -----------------------------------------------
//    startDownload
// -----------------------------------------------
- (void)startDownload{
    NSURL *url = [NSURL URLWithString:self.hotSongInfo.pic_small];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error != nil) {
            if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection) {
                abort();
            }
        }
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
              // Set appIcon and clear temporary data/image
            UIImage *image = [[UIImage alloc] initWithData:data];
            if (image.size.width != kAppIconSize || image.size.height != kAppIconSize) {
                CGSize itemSize = CGSizeMake(kAppIconSize, kAppIconSize);
                
                UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
                CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
                [image drawInRect:imageRect];
                self.hotSongInfo.albumImage_small = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
            }
            else{
                self.hotSongInfo.albumImage_small = image;
            }
            if (self.completionHandler != nil) {
                self.completionHandler();
            }
        }];
    }];
    [self.sessionTask resume];
}

// ------------------------------------------------
//    cancelDownload
// ------------------------------------------------
- (void)cancelDownload{
    [self.sessionTask cancel];
    _sessionTask = nil;
}


// -------------------------------------------------------------------------------
//    handleError:error
//  Reports any error with an alert which was received from connection or loading failures.
// -------------------------------------------------------------------------------
- (void)handleError:(NSError *)error{
    NSString *errorMessage = [error localizedDescription];
    // alert user that our current record was deleted, and then we leave this view controller
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Cannot Show Top Paid Apps"
                                                                   message:errorMessage
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"OK"
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction *action) {
                                                         // dissmissal of alert completed
                                                     }];
    [alert addAction:OKAction];
}

@end
